package com.ub.party.web.base;

import com.ub.party.web.constants.ShreecConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Ran.Han on 16-5-25.
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private CookieHelper cookieHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if (!isSessionCheck(handler)) {
//            return true;
//        }
        boolean sessionLive = isSessionLive(request);

//        if (!sessionLive) {
//            response.sendRedirect("/admin/index");
//        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private boolean isSessionLive(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (null == session) {
            return false;
        }
        Object sessionKey = session.getAttribute(ShreecConstants.SHREEC_SESSION_KEY);
        if (null == sessionKey) {
            return false;
        }
        String cookieValue = cookieHelper.getCookieValue(request, ShreecConstants.SHREEC_SESSION_KEY);
        if (!sessionKey.toString().equals(cookieValue)) {
            return false;
        }
        return true;
    }

    private boolean isSessionCheck(Object handler) {
        return handler instanceof HandlerMethod && (((HandlerMethod) handler).getMethodAnnotation(SessionCheck.class) != null || ((HandlerMethod) handler).getBeanType().isAnnotationPresent(SessionCheck.class));
    }
}
